package com.atguigu.reggie.service.impl;

import com.atguigu.reggie.common.BaseContext;
import com.atguigu.reggie.entity.*;
import com.atguigu.reggie.mapper.OrdersMapper;
import com.atguigu.reggie.selfException.CustomException;
import com.atguigu.reggie.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-10-26 20:02
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;
    /**
     * 提交订单
     */
    public void submit(Orders orders){
        // 获取当前用户id
        Long currentId = BaseContext.getCurrentId();

        // 获取用户信息
        User user = userService.getById(currentId);

        // 获取当前用户的购物车信息
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,currentId);

        // SQL:select * from shopping_cart where user_id = ?
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);

        // 判断购物车是否为空
        if (shoppingCartList == null || shoppingCartList.size() == 0){
            throw new CustomException("当前购物车为空，不能下单");
        }

        // 获取当前用户的默认地址信息
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,currentId);
        addressBookLambdaQueryWrapper.eq(AddressBook::getIsDefault,1);

        // SQL:select * from address_book where user_id = ? and is_default = 1;
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);

        // 判断地址是否为空
        if (addressBook == null){
            throw new CustomException("当前地址为空,不能下单");
        }

        // 保证线程安全
        AtomicInteger amount = new AtomicInteger(0);

        // 获取一个订单号
        long orderId = IdWorker.getId();

        // 构建orderDetails
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) ->{
            // 创建一个OrderDetail对象
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 构建orders
        // 向订单表插入数据，一条数据
        orders.setId(orderId);
        // 下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 支付时间
        orders.setCheckoutTime(LocalDateTime.now());
        // 2：带派送
        orders.setStatus(2);
        // 订单的总金额
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(user.getId());
        orders.setNumber(String.valueOf(currentId));
        orders.setUserName(addressBook.getConsignee());
        // 设置收货人
        orders.setConsignee(addressBook.getConsignee());
        // 设置订单电话
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.clean();
    }
}
